from rest_framework.serializers import ModelSerializer, SerializerMethodField
from school.models import Classes
from user.serializers import UserSerializer


# 序列化
class ClassesSerializer(ModelSerializer):
    # member = UserSerializer(many=True)  # 展示多条
    member_detail = SerializerMethodField()

    class Meta:
        model = Classes
        exclude = ['is_delete']

        extra_kwargs = {
            'member': {'write_only': True}  # 只写==只反序列化
        }

    def get_member_detail(self, classes):  # 函数名一定得是 'get' + '_' + '对应的方法'
        serializer = UserSerializer(classes.member.all(), many=True)
        data = {
            # 分组 老师组的id是1,学生组的id是2
            'teacher': [i for i in serializer.data if 1 in i['groups'] or i['is_superuser']],
            'student': [i for i in serializer.data if 2 in i['groups']]
        }
        return data
